#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author : zaniu(zzaniu@126.com)
# @Time   : 2021/6/26 21:12 
# @Desc   :
# 
#                   _ooOoo_
#                  o8888888o
#                  88" . "88
#                  (| -_- |)
#                  O\  =  /O
#               ____/`---'\____
#             .'  \\|     |//  `.
#            /  \\|||  :  |||//  \
#           /  _||||| -:- |||||-  \
#           |   | \\\  -  /// |   |
#           | \_|  ''\---/''  |   |
#           \  .-\__  `-`  ___/-. /
#         ___`. .'  /--.--\  `. . __
#      ."" '<  `.___\_<|>_/___.'  >'"".
#     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
#     \  \ `-.   \_ __\ /__ _/   .-` /  /
# =====`-.____`-.___\_____/___.-`____.-'=====
#                   `=---='
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#             佛祖保佑       永无BUG
#
import json
from time import sleep
import nacos

SERVER_ADDRESS = "172.18.2.249:8848"
NAMESPACE = "91fbf3ef-c56c-4fa5-8c6d-c5255c708d2a"

# 这里发现不写用户名密码也可以，应该是配置出问题了
client = nacos.NacosClient(SERVER_ADDRESS, namespace=NAMESPACE, username="nacos", password="nacos")


def get_config(data_id: str, group: str, *args, **kwargs):
    # client.publish_config()  # 发布配置
    # client.remove_config()  # 删除配置
    # client.remove_config_watcher()  # 删除监听
    return client.get_config(data_id, group, *args, **kwargs)


def watch_hander(data):
    """当配置文件发生改变的时候调用该函数"""
    print("配置文件发生改变")
    # data = json.loads(data)
    print(f"data = {data}, type = {type(data)}, len = {len(data)}")
    print(f"data['content'] = {data['content']}, type = {type(data['content'])}")
    new_conf = json.loads(data['content'])
    print(f"new_conf = {new_conf}, type = {type(new_conf)}")


def test_watch(data_id: str, group: str):
    """监听配置文件信息"""
    client.add_config_watcher(data_id, group, watch_hander)


if __name__ == '__main__':
    # data_id = "user_conf.yaml"
    data_id = "user.json"
    group = "dev"
    ret = get_config(data_id, group)
    # 这里类型是一个str，感觉用json可能会方便一些
    print(f"ret = {ret}, type = {type(ret)}")
    test_watch(data_id, group)
    sleep(200)
